package me.yricky.alia.ui.fileListPage

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Window
import me.yricky.alia.App
import me.yricky.alia.ui.AliaIcons
import me.yricky.alia.ui.WindowInst
import me.yricky.alia.ui.component.FileList

/**
 * @author Yricky
 * @date 2022/1/29
 */
object FileListPageFactory {

    fun getWindowInst(path:String = "~"):WindowInst{
        return object : WindowInst() {
            val viewModel: FileListViewModel = FileListViewModel().also {
                it.setPath(path)
                it.setOpenMethods(App.internalOpenMethods)
            }

            override fun tag(): String {
                return viewModel.viewState.currDir.value.canonicalPath
            }

            @Composable
            override fun window() {
                val currDir by viewModel.viewState.currDir.collectAsState()
                Window(
                    title = currDir.canonicalPath,
                    icon = AliaIcons.defaultWindowIcon(),
                    onCloseRequest = { App.removeWindow(this) }) {
                    Page(viewModel)
                }
            }
        }
    }

    @Composable
    fun Page(viewModel: FileListViewModel){
        val filter by viewModel.viewState.filter.collectAsState()
        val files by viewModel.viewState.files.collectAsState()
        val openMethod by viewModel.viewState.openMethod.collectAsState()
        val res by App.res.collectAsState()
        Column(
            Modifier
                .fillMaxSize()
        ) {
            OutlinedTextField(
                filter,
                {viewModel.setFilter(it.trim())},
                label = { Text(res.str.filter) },
                modifier = Modifier.padding(8.dp,0.dp).fillMaxWidth())
            FileList(Modifier
                .weight(1f)
                .fillMaxWidth()
                .padding(8.dp),
                files.filter { it.contains(filter,true) }
            ){ f->
                if(f.isDirectory){
                    viewModel.setPath(f.path)
                }else{
                    openMethod[
                            (f.name.split(".").lastOrNull() ?: "").uppercase()
                    ]?.invoke(f.canonicalPath)
                }
            }
        }

    }
}